<template>
  <div class="common-container px_8">
    <el-breadcrumb separator="/" class="pt_8 pb_16">
      <el-breadcrumb-item @click="handleBack">数据集</el-breadcrumb-item>
      <el-breadcrumb-item>ETL</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :label-width="80" label-placement="left" :model="query" size="small">
      <el-form-item label="名称:" path="name">
        <el-input placeholder="请输入ETL名称" v-model.trim="query.name" @keyup.enter.native="getMyETLList" clearable
          @change="getMyETLList" />
      </el-form-item>
      <el-form-item label="数据源:" path="data_source_id">
        <el-select style="width: 140px" placeholder="请选择数据源" v-model="query.data_source_id" clearable
          @change="getMyETLList">
          <el-option v-for="item in sourceList" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="备注:" prop="remark">
        <el-input placeholder="请输入备注" v-model.trim="query.remark" @keyup.enter.native="getMyETLList" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="getMyETLList">
          <el-icon style="vertical-align: middle;">
            <Search></Search>
          </el-icon>
          <span style="vertical-align: middle;">查询</span>
        </el-button>
        <el-button type="success" @click="handleModalAddAction">
          <el-icon style="vertical-align: middle;">
            <CirclePlus></CirclePlus>
          </el-icon>
          <span style="vertical-align: middle;">新增</span>
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="ETLList" border class="w_100" v-loading="ETLLoading">
      <el-table-column type="index" width="50" label="序号" align="center" />
      <el-table-column property="name" align="center" label="名称" />
      <el-table-column align="center" property="data_source_name" label="数据源名称" />
      <el-table-column property="data_source_type" align="center" label="数据源类型">
        <template #default="scope">
          <el-tag effect="dark" size="small" :type="showType(scope.row.data_source_type)">{{
              scope.row.data_source_type
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" property="status" label="状态">
        <template #default="scope">
          <el-tag type="success" size="small" v-if="scope.row.status">已完成</el-tag>
          <el-tag type="warning" size="small" v-if="!scope.row.status">草稿</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" property="remark" label="备注" />
      <el-table-column align="center" property="create_timestamp" label="创建时间">
        <template #default="scope">
          <span>{{ formatTime(scope.row.create_timestamp) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <!--          <el-button size="small" type="success" @click="handleModalEditAction(scope.row)">更新-->
          <!--          </el-button>-->
          <el-button type="success" size="small" class="cursor_point" v-if="scope.row.status === 1"
            v-loading="formLoading" @click="handleTestAPI(scope.row)">测试
          </el-button>
          <el-button size="small" v-if="scope.row.status === 0" type="success" plain @click="designETL(scope.row)">设计
          </el-button>
          <el-button size="small" v-if="scope.row.status === 1" type="success" plain @click="designETL(scope.row)">查看
          </el-button>
          <el-button size="small" type="danger" @click="handleModalDelAction(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="mt_16 right" v-model:currentPage="query.size" :page-size="query.limit"
      layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange"></el-pagination>
    <el-drawer v-model="ETLOpModel" :title="modalTitle[modalStatus]" size="28%" direction="rtl">
      <el-form :model="etlForm" :rules="rules" ref="etlFormRef" label-placement="left" label-width="80px" size="small">
        <el-form-item label="名称:" path="name">
          <el-input placeholder="请输入名称" v-model.trim="etlForm.name" clearable />
        </el-form-item>
        <el-form-item label="数据源:" path="data_source_id">
          <el-select placeholder="请选择数据源" v-model="etlForm.data_source_id" clearable filterable class="w_100">
            <el-option v-for="item in sourceList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:" path="remark">
          <el-input placeholder="请输入备注" type="textarea" v-model.trim="etlForm.remark" clearable />
        </el-form-item>
      </el-form>
      <div class="footer-modal fixed bottom_0 p_8 text_right right_0">
        <el-button @click="handleCloseModal" v-loading="formLoading" size="small" class="footer-modal--btn">取消
        </el-button>
        <el-button v-if="modalStatus ==='add'" type="success" size="small" v-loading="formLoading"
          class="footer-modal--btn  base-primary-btn m_lr_10" @click="handleAddETL">确认
        </el-button>
        <el-button v-if="modalStatus ==='edit'" type="success" size="small" v-loading="formLoading"
          class="footer-modal--btn  base-primary-btn m_lr_10" @click="handleEditETL">更新
        </el-button>
      </div>
    </el-drawer>
    <el-dialog v-model="checkModal" title="测试结果" width="75%" destroy-on-close>
      <vxe-table v-loading="tableDataLoading" :tooltip-config="tableTooltipConfig" :element-loading-spinner="loadingSvg"
        element-loading-text="加载中..." element-loading-background="rgba(0, 0, 0, 0.8)"
        element-loading-svg-view-box="0, 0, 50, 50" border="full" height="500px" show-header-overflow
        :column-config="{resizable: true}" show-overflow :row-config="{isHover: true}" :data="requestData">
        <vxe-column align="center" type="seq" width="60" field="序号" fixed></vxe-column>
        <vxe-column align="center" v-for="column in requestColumns" :key="column" :title="column" :field="column"
          sortable min-width="150"></vxe-column>
      </vxe-table>
      <template #footer>
        <el-button @click="checkModal = false" plain size="small" class="cursor_point">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, onMounted, reactive, ref } from "vue";
import {
  addDataETL,
  delDataETL,
  editDataETL,
  etlExec,
  getDataETLList,
} from "../../../service/data_etl";
import { allDataSource } from "../../../service/source";
import { useRouter } from "vue-router";
import { CirclePlus, Search } from "@element-plus/icons-vue";
import { formatDate } from "../../../utils/utils";
import { loadingSvg } from "../../../utils/constant";

export default defineComponent({
  name: "my-data-etl",
  components: {
    CirclePlus,
    Search,
  },
  setup() {
    const router = useRouter();
    const ETLList = ref([]);
    const total = ref(0);
    const formatTime = (num) => {
      return formatDate(num, "yyyy-MM-dd hh:mm:ss");
    };
    const ETLOpModel = ref(false);
    const ETLLoading = ref(false);
    const checkModal = ref(false);
    const requestData = ref([]);
    const formLoading = ref(false);
    const modalStatus = ref("add");
    const tableDataLoading = ref(false);
    const requestColumns = ref([]);
    const tableTooltipConfig = reactive({
      showAll: true,
      enterable: true,
      contentMethod: ({ type, column, row, items, _columnIndex }) => {
        const { property } = column;
        // 重写默认的提示内容
        if (property === "role" || property === "date") {
          if (type === "header") {
            return column.title ? column.title : "";
          }
          return row[property] ? row[property] : "";
        }
        // 其余的单元格使用默认行为
        return null;
      },
    });
    const sourceList = ref([]);
    const modalTitle = ref({
      add: "新增ETL",
      edit: "编辑ETL",
    });
    const query = ref({
      limit: 10,
      size: 1,
      name: "",
      remark: "",
      data_source_id: "",
    });
    const handleSizeChange = (pageSize) => {
      query.value.size = 1;
      query.value.limit = pageSize;
      getMyETLList();
    };
    const handleCurrentChange = (limit) => {
      query.value.limit = limit;
      getMyETLList();
    };
    const etlForm = ref({
      name: undefined,
      data_source_id: "",
      remark: undefined,
    });
    const etlFormRef = ref(null);
    const resetForm = () => {
      etlForm.value = {
        name: undefined,
        data_source_id: "",
        remark: undefined,
      };
    };
    const handleModalAddAction = () => {
      resetForm();
      modalStatus.value = "add";
      ETLOpModel.value = true;
    };
    const getMyETLList = () => {
      ETLLoading.value = true;
      getDataETLList(query.value).then((res) => {
        ETLList.value = res.data.result;
        ETLLoading.value = false;
        total.value = res.data.total;
      });
    };
    const handleAddETL = () => {
      formLoading.value = true;
      etlFormRef.value.validate((valid) => {
        if (valid) {
          addDataETL(etlForm.value)
            .then(() => {
              formLoading.value = false;
              ElMessage({
                type: "success",
                message: "新增ETL成功",
              });
              handleCloseModal();
              getMyETLList();
            })
            .catch(() => {
              formLoading.value = false;
            });
        } else {
          formLoading.value = false;
        }
      });
    };
    const handleModalEditAction = (rowData) => {
      resetForm();
      etlForm.value = rowData;
      modalStatus.value = "edit";
      ETLOpModel.value = true;
    };
    const handleEditETL = () => {
      formLoading.value = true;
      etlFormRef.value.validate((valid) => {
        if (valid) {
          editDataETL(etlForm.value)
            .then(() => {
              formLoading.value = false;
              ElMessage({
                type: "success",
                message: "编辑ETL成功",
              });
              handleCloseModal();
              getMyETLList();
            })
            .catch(() => {
              ElMessage.error("编辑ETL失败");
              formLoading.value = false;
            });
        } else {
          formLoading.value = false;
        }
      });
    };
    const handleModalDelAction = (rowData) => {
      ElMessageBox.confirm(`你确定删除 ${rowData.name} 么？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        handleDelETL(rowData);
      });
    };
    const handleDelETL = (rowData) => {
      delDataETL({ data_etl_id: rowData.data_etl_id })
        .then(() => {
          ElMessage({
            type: "success",
            message: "删除ETL成功",
          });
          getMyETLList();
        })
        .catch((err) => {
          ElMessage.error("删除ETL失败");
        });
    };
    const handleBack = () => {
      router.push({ path: "index" });
    };
    const handleAllSource = () => {
      allDataSource().then((res) => {
        sourceList.value = res.data.result;
      });
    };
    const showType = (type) => {
      let tagType;
      switch (type) {
        case "PostgreSQL":
          tagType = "";
          break;
        case "Oracle":
          tagType = "info";
          break;
        case "MySQL":
          tagType = "warning";
          break;
        default:
          break;
      }
      return tagType;
    };
    const designETL = (rowData) => {
      let etlPage = router.resolve({
        path: "/etl",
        query: { id: rowData.data_etl_id },
      });
      window.open(etlPage.href, "_blank");
    };
    const handleTestAPI = (row) => {
      checkModal.value = true;
      tableDataLoading.value = true;
      requestData.value = [];
      requestColumns.value = [];
      etlExec({ data_etl_id: row.data_etl_id })
        .then((res) => {
          ElMessage({
            type: "success",
            message: "查询ETL成功",
          });
          requestData.value = res.data;
          if (res.data.length) {
            requestColumns.value = Object.keys(res.data[0]);
          }
          tableDataLoading.value = false;
        })
        .catch((err) => {
          tableDataLoading.value = false;
          ElMessage.error("查询ETL失败");
        });
    };
    const handleCloseModal = () => {
      ETLOpModel.value = false;
    };
    onMounted(() => {
      getMyETLList();
      handleAllSource();
    });
    return {
      rules: {
        name: {
          required: true,
          trigger: ["blur", "input"],
          message: "请输入etl名称",
        },
      },
      checkModal,
      query,
      total,
      ETLList,
      showType,
      ETLOpModel,
      etlForm,
      etlFormRef,
      modalStatus,
      modalTitle,
      sourceList,
      formLoading,
      ETLLoading,
      tableDataLoading,
      tableTooltipConfig,
      loadingSvg,
      requestColumns,
      handleTestAPI,
      formatTime,
      getMyETLList,
      handleCloseModal,
      handleModalAddAction,
      resetForm,
      handleDelETL,
      handleModalDelAction,
      handleModalEditAction,
      handleAddETL,
      handleEditETL,
      handleBack,
      handleAllSource,
      handleSizeChange,
      handleCurrentChange,
      designETL,
      requestData,
    };
  },
});
</script>

<style lang="less" scoped>
.request-content {
  .request-content_title {
    font-size: 14px;
    margin: 12px 0 12px;
    font-weight: bolder;
  }
}
</style>
